import os,json
from datetime import date, datetime
import requests
import pymysql
import threading
from DBUtils.PooledDB import PooledDB
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import sys
import configparser
import socket

dir_path = os.path.dirname(os.path.abspath(__file__))

def get_config(group,config_name):
    config = configparser.ConfigParser()
    conf_file = os.path.join(dir_path,"..","..","conf","config.ini")
    config.read(conf_file)
    config_value=config.get(group,config_name).strip(' ').strip('\'').strip('\"')
    return config_value

class SingletonDBPool(object):
    _instance_lock = threading.Lock()

    def __init__(self):
        # print("单例数据库连接初始化")
        dialect = get_config('mysql','dialect')
        mysql_driver = get_config('mysql','driver')
        mysql_host=get_config('mysql','host')
        mysql_port=int(get_config('mysql','port'))
        mysql_username=get_config('mysql','user')
        mysql_password=get_config('mysql','pass')
        mysql_database=get_config('mysql','database')
        # print(mysql_host,mysql_port,mysql_username,mysql_password,mysql_database)
        # mysql://user:password@hostname:port/dbname?charset=utf8
        db_uri = "{}+{}://{}:{}@{}:{}/{}?charset=utf8".format(
            dialect,mysql_driver,mysql_username,mysql_password,mysql_host,mysql_port,mysql_database
        )
        # print(db_uri)
        self.engine = create_engine(db_uri,echo=False,pool_size=8,pool_recycle=60*30)


    def __new__(cls, *args, **kwargs):
        if not hasattr(SingletonDBPool, "_instance"):
            with SingletonDBPool._instance_lock:
                if not hasattr(SingletonDBPool, "_instance"):
                    SingletonDBPool._instance = object.__new__(cls, *args, **kwargs)
        return SingletonDBPool._instance

    def connect(self):
        DbSession = sessionmaker(bind=self.engine)
        return DbSession()


def http_request(url=None,headers=None,data=None,timeout=None,method=None):
    res = None
    try:
        if method=='post':
            res = requests.post(url,data=data,headers=headers,timeout=timeout)
        else:
            res = requests.get(url,data=data,headers=headers,timeout=timeout)
    except Exception as e:
        print(e)
    if res and res.status_code == 200:
        return res.json()
    else:
        if res is not None and res.status_code:
            status = res.status_code
            res = res.json()
        else:
            status = 500
        return  {'status':status,'后台返回': res}
